package org.agile4j.patterns.command.macros;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 读写文件的补助工具类
 * @author user
 *
 */
public class FileOpeUtil {

	/**
	 * 私有化构造方法, 避免外部无谓的创建类实例
	 * 这个工具类不需要创建实例	
	 */
	private FileOpeUtil(){}
	
	/**
	 * 读文件, 从文件中获取存储的List对象
	 * @param pathName 文件路径和文件名
	 * @return 
	 */
	public static List<?> readFile(String pathName){
		List<?> list = new ArrayList() ;
		ObjectInputStream oin = null ;
		File file  = new File(pathName) ;
		try {
			if(file.exists()){
				// BufferedInputStream 据说提高速度. . . 
				oin = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))) ;
				list = (List<?>)oin.readObject() ;
			} 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (oin != null){
					oin.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list ;
	}
	
	/**
	 * 写文件, 把List对象写到文件中
	 * @param pathName 文件路径和文件名
	 * @param list 要写入到文件的List对象
	 */
	public static void writeFile(String pathName, List<?> list){
		ObjectOutputStream oout = null ; 
		try {
			File file = new File(pathName) ;
			oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file))) ;
			oout.writeObject(list);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(oout != null){
					oout.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
